<template>
  <commonDrawer
          :title="drawerData.type==='add'?'新建自动外呼任务':'更新自动外呼任务'"
          :drawer="drawer"
          :appendToBody="true"
          @closeDraw="openOrCloseDrawer('close')"
          @cancelFun="drawer=false"
          @save="submitForm">
    <template slot="column">
      <el-form :model="baseFrom" :rules="rules" ref="formRef" label-position="top" size="mini">
        <el-form-item label="任务名称" prop="name">
          <el-input size="mini" type="text" v-model.trim="baseFrom.name" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input size="mini" type="textarea" v-model.trim="baseFrom.description" placeholder="请输入描述"></el-input>
        </el-form-item>
        <!-- 呼叫策略表单 start -->
        <el-form :model="callStrategy" :rules="callStrategyRules" ref="callStrategyRef" label-position="top" size="mini">
          <el-form-item label="呼叫策略" prop="concurrentType">
            <el-radio v-model="callStrategy.concurrentType" :disabled="drawerData.type!=='add'" label="stable">固定并发</el-radio>
            <el-radio v-model="callStrategy.concurrentType" :disabled="drawerData.type!=='add'" label="dynamic">动态并发</el-radio>
          </el-form-item>
          <el-form-item v-if="callStrategy.concurrentType === 'dynamic'" prop="freeAgentCount">
              <span slot="label" prop="freeAgentCount">
                  空闲座席数的倍数
                <el-tooltip class="item" effect="dark" content="请输入大于0的倍数" placement="top">
                  <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
                </el-tooltip>
              </span>
            <el-input size="mini" type="number" :disabled="drawerData.type!=='add'" v-model.trim="callStrategy.freeAgentCount" placeholder="请输入空闲座席数的倍数"></el-input>
          </el-form-item>
          <el-form-item label="" v-if="callStrategy.concurrentType === 'dynamic'" prop="maxConcurrent">
            <span slot="label">
              该任务最大并发数
              <el-tooltip class="item" effect="dark" content="当智能并发数大于固定并发数时，以固定并发数为最大并发" placement="top">
                <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
              </el-tooltip>
            </span>
            <el-input size="mini" type="number" :disabled="drawerData.type!=='add'" v-model.trim="callStrategy.maxConcurrent" placeholder="请输入该任务最大并发数"></el-input>
          </el-form-item>
          <el-form-item label="" v-if="callStrategy.concurrentType === 'stable'" prop="concurrent">
            <span slot="label">
              并发数
              <el-tooltip class="item" effect="dark" :content="concurrentStr" placement="top">
                <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
              </el-tooltip>
            </span>
            <el-input size="mini" type="number" :disabled="drawerData.type!=='add'" v-model.trim="callStrategy.concurrent" placeholder="请输入并发数"></el-input>
          </el-form-item>
        </el-form>
        <!-- 呼叫策略表单 end -->
        <el-form-item label="优先级" prop="priority">
          <el-input size="mini" type="number" :disabled="drawerData.type!=='add'"  v-model.trim="baseFrom.priority" placeholder="请输入正整数，1为最高优先级"></el-input>
        </el-form-item>
        <el-form-item label="启动方式" prop="startType">
          <el-radio v-model="baseFrom.startType" :disabled="drawerData.type!=='add'" label="manual">手动启动</el-radio>
          <el-radio v-model="baseFrom.startType" :disabled="drawerData.type!=='add'" label="timing">定时启动</el-radio>
        </el-form-item>
        <el-form-item label="" prop="timingStartTime" v-if="baseFrom.startType === 'timing'">
           <el-date-picker
            :disabled="drawerData.type!=='add'"
            v-model="baseFrom.timingStartTime"
            type="datetime"
            :picker-options="pickerOptions"
            placeholder="定时启动时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="" prop="timeConditionId">
          <span slot="label">
            运行时间
            <el-tooltip class="item" effect="dark" content="为避免投诉导致线路不可用，建议设置为9:00-20:00之间外呼" placement="top">
              <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
            </el-tooltip>
          </span>
          <m7Select size="mini" v-model="baseFrom.timeConditionId" placeholder="请选择运行时间" filterable :options="timeConditionList" :defaultProps="{label: 'name', value: '_id'}"></m7Select>
        </el-form-item>
        <el-form-item label="语音导航" prop="ivrId">
          <m7Select size="mini" v-model="baseFrom.ivrId" :disabled="drawerData.type!=='add'" placeholder="请选择语音导航" filterable :options="voiceNavArr" :defaultProps="{label: 'name', value: '_id'}"></m7Select>
        </el-form-item>
        <el-form-item label="主叫号码" prop="numberType">
          <el-radio v-model="baseFrom.numberType" label="number">号码</el-radio>
          <el-radio v-model="baseFrom.numberType" label="group">号码组</el-radio>
        </el-form-item>
        <el-form-item label="" prop="numberList" v-if="baseFrom.numberType === 'number'" >
          <m7Select size="mini"  v-model="baseFrom.numberList" placeholder="请选择号码" multiple filterable :options="displayNumerList" :defaultProps="{label: 'number', value: '_id'}"></m7Select>
        </el-form-item>
        <el-form-item label="" prop="groupList" v-if="baseFrom.numberType === 'group'" >
          <m7Select size="mini" v-model="baseFrom.groupList" placeholder="请选择号码组" multiple filterable :options="groupList" :defaultProps="{label: 'name', value: '_id'}"></m7Select>
        </el-form-item>
        <el-form-item label="" prop="timeOut">
          <span slot="label">
            振铃时间限制
            <el-tooltip class="item" effect="dark" content="请输入大于20 的数值，请谨慎进行设置，设置后，在电话自动外呼出去后，如果被叫在所设置的时间内，没有接听电话，将会自动挂断，提高通话效率" placement="top">
              <span class="V7_iconfont V7_iconV7tubiao_bangzhu-42 tip-span"></span>
            </el-tooltip>
          </span>
          <el-input size="mini" type="number"  v-model.trim="baseFrom.timeOut" placeholder="请输入振铃时间限制">
            <span slot="suffix">秒</span>
          </el-input>
        </el-form-item>
        <div class="repeat-call">
          <el-switch v-model="baseFrom.openRepeatCall" active-color="#2ED47A" active-text="重呼机制" :disabled="drawerData.type!=='add'"></el-switch>
        </div>
        <!-- 重呼机制表单 start -->
        <el-form :model="repeatCallConfig" :rules="repeatCallRules" ref="repeatCallRef" label-position="top" size="mini">
          <div v-if="baseFrom.openRepeatCall">
            <el-form-item label="通话结果" prop="callResult">
              <m7Select size="mini" v-if="drawerData.type==='add'"  v-model="repeatCallConfig.callResult"  placeholder="请选择通话结果" multiple filterable :options="callResultArr"></m7Select>
              <selectEcho
                v-else
                :propValue="repeatCallConfig.callResult"
                :options="callResultArr"
              ></selectEcho>
            </el-form-item>
            <el-form-item label="重呼次数" prop="repeatCount">
              <m7Select size="mini" v-model="repeatCallConfig.repeatCount" :disabled="drawerData.type!=='add'" placeholder="请选择重呼次数" filterable :options="repeatCallArr" :defaultProps="{label: 'name', value: 'name'}" @change="changeRepeatCall"></m7Select>
            </el-form-item>
            <el-form-item label="重呼间隔" prop="repeatIntervalType">
              <el-radio v-model="repeatCallConfig.repeatIntervalType" :disabled="drawerData.type!=='add'" label="afterNumber">号码后重呼</el-radio>
              <el-radio v-model="repeatCallConfig.repeatIntervalType" :disabled="drawerData.type!=='add'" label="afterTask">任务后重呼</el-radio>
            </el-form-item>
            <ul v-if="repeatCallConfig.repeatCount > 0" class='repeat-call-ul clearfix'>
              <li v-for="index in 2" :key="index" class="fl">
                <span class='time-span'>次数</span>
                <span class="interval-span">重呼间隔(min)</span>
              </li>
              <li v-for="(item, index) in repeatCallConfig.repeatCount" :key="index" class="fl">
                <span class='time-span' v-if="repeatCallConfig.frequencyConfig[index]">{{index + 1}}</span>
                <el-input type="number" :disabled="drawerData.type!=='add'" v-if="repeatCallConfig.frequencyConfig[index]" :disabeld="drawerData.type==='edit'" class="interval-span interval-input" size="mini" v-model.trim="repeatCallConfig.frequencyConfig[index].interval"></el-input>
              </li>
            </ul>
          </div>
        </el-form>
        <!-- 重呼机制表单 end -->
      </el-form>
    </template>
  </commonDrawer>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import commonDrawer from '@/common/views/drawer/index.vue'
import selectEcho from '@components/select/selectEcho.vue'
import { commonAction, getFormatDateTime } from '@/utils/common'
import cloneDeep from 'lodash/cloneDeep'
interface DrawObj {
  type: string
  title: string
  form: any
}
@Component({
  name: 'autoEditOrAdd',
  components: { commonDrawer, selectEcho }
})
export default class PriviewEditOrAdd extends Vue {
  @Prop({
    default: () => {
      return {}
    }
  }) private drawerData!: DrawObj

  private drawer: boolean = false
  private $getCache: any
  private $store: any
  private $message: any
  private pickerOptions: any = {
    disabledDate (time) {
      return time && time.getTime() < Date.now() - 8.64e7
    }
  }

  private concurrentStr: string = ''
  private voiceNavArr: object[] = [{}] // 语音导航数据列表
  private timeConditionList: object[] = [{}] // 时间条件列表
  private displayNumerList: object[] = [{}] // 外显号列表
  private groupList: object[] = [{}] // 外显号列表
  private callResultArr: object[] = [
    { label: '禁止呼叫', value: 'forbidden' },
    { label: '服务不可用', value: 'serviceUnavailable' },
    { label: '请求终止', value: 'cancel' },
    { label: '呼叫超时', value: 'requestTimeout' },
    { label: '未识别', value: 'unknow' },
    { label: '被叫未接听', value: 'decline' },
    { label: '被叫忙', value: 'calledBusy' },
    { label: '空号', value: 'notFound' }
  ]

  private repeatCallArr: object[] = [{ name: 1 }, { name: 2 }, { name: 3 }, { name: 4 }, { name: 5 }]

  private repeatCallConfig: any = {
    callResult: [],
    repeatCount: 1,
    repeatIntervalType: 'afterNumber',
    frequencyConfig: [{ frequency: 1, interval: '' }]
  }

  private callStrategy: any = {
    freeAgentCount: 1,
    concurrentType: 'stable',
    concurrent: 1,
    maxConcurrent: 1
  }

  private baseFrom: any = {
    _id: '',
    name: '',
    description: '',
    priority: 1,
    startType: 'manual',
    timingStartTime: '',
    timeConditionId: '',
    ivrId: '',
    numberType: 'number',
    numberList: [],
    groupList: [],
    timeOut: 20,
    openRepeatCall: false
  }

  private allFrom: any = { repeatCallConfig: cloneDeep(this.repeatCallConfig), callStrategy: cloneDeep(this.callStrategy), baseFrom: cloneDeep(this.baseFrom) }

  private rules = {
    name: [
      { required: true, message: '请输入活动名称', trigger: 'blur' },
      { min: 2, max: 40, message: '长度在 2 到 40 个字符', trigger: 'blur' }
    ],
    numberType: [
      { required: true, message: '请选择主叫号码', trigger: 'change' }
    ],
    ivrId: [
      { required: true, message: '请选择语音导航', trigger: 'change' }
    ],
    timeConditionId: [
      { required: true, message: '请选择运行时间', trigger: 'change' }
    ],
    startType: [
      { required: true, message: '请选择启动方式', trigger: 'change' }
    ],
    numberList: [
      { required: true, message: '请选择号码', trigger: 'change' }
    ],
    groupList: [
      { required: true, message: '请选择号码组', trigger: 'change' }
    ],
    priority: [
      { required: true, message: '请输入任务优先级', trigger: 'blur' }
    ],
    timingStartTime: [
      { required: true, message: '请选择定时启动时间', trigger: 'change' }
    ]
  }

  private callStrategyRules = {
    concurrentType: [
      { required: true, message: '请选择呼叫策略', trigger: 'change' }
    ],
    freeAgentCount: [
      { required: true, message: '请输入大于0的倍数', trigger: 'blur' }
    ],
    maxConcurrent: [
      { required: true, message: '请输入该任务最大并发数', trigger: 'blur' }
    ],
    concurrent: [
      { required: true, message: '请输入账户并发数', trigger: 'blur' }
    ]
  }

  private repeatCallRules = {
    callResult: [
      { required: true, message: '请选择通话结果', trigger: 'change' }
    ],
    repeatCount: [
      { required: true, message: '请选择重呼次数', trigger: 'change' }
    ],
    repeatIntervalType: [
      { required: true, message: '请选择重呼间隔', trigger: 'change' }
    ]
  }

  public openOrCloseDrawer (data: any) {
    this.drawer = !this.drawer
    if (data === 'close') {
      return
    }
    if (Object.keys(data).length > 0) { // 编辑
      Object.keys(this.baseFrom).forEach((key) => {
        this.baseFrom[key] = data[key]
      })
      this.callStrategy = data.callStrategy
      this.repeatCallConfig = data.repeatCallConfig
    } else { // 新增
      this.baseFrom = cloneDeep(this.allFrom.baseFrom)
      this.callStrategy = cloneDeep(this.allFrom.callStrategy)
      this.repeatCallConfig = cloneDeep(this.allFrom.repeatCallConfig)
    }
    this.$nextTick(() => {
      const self = (this as any)
      self.$refs.formRef.clearValidate()
      self.$refs.callStrategyRef.clearValidate()
      self.$refs.repeatCallRef.clearValidate()
    })
  }

  private changeRepeatCall (data) {
    this.repeatCallConfig.frequencyConfig = []
    for (let i = 0; i < data; i++) {
      this.repeatCallConfig.frequencyConfig.push({ frequency: i + 1, interval: '' })
    }
  }

  private handleStrToNumber () {
    this.baseFrom.priority = Number(this.baseFrom.priority)
    this.baseFrom.timeOut = Number(this.baseFrom.timeOut)
    this.callStrategy.freeAgentCount = Number(this.callStrategy.freeAgentCount)
    this.callStrategy.concurrent = Number(this.callStrategy.concurrent)
    this.callStrategy.maxConcurrent = Number(this.callStrategy.maxConcurrent)
    let errMessage = ''
    if (this.baseFrom.timingStartTime) { // 自动开启时间
      this.baseFrom.timingStartTime = getFormatDateTime(this.baseFrom.timingStartTime, '')
    }
    if (this.baseFrom.openRepeatCall) { // 开启了重呼机制
      this.repeatCallConfig.frequencyConfig.forEach((item: any, index: number) => {
        if (!item.interval) {
          errMessage = `重呼次数 ${index + 1} 的重呼间隔不能为空`
          return false
        } else {
          item.interval = Number(item.interval)
          if (item.interval < 1 || item.interval > 60) {
            errMessage = `重呼次数 ${index + 1} 的重呼间隔范围为1~60min`
            return false
          }
        }
      })
    }
    return errMessage
  }

  private submitForm () {
    (this.$refs as any).formRef.validate((valid) => {
      if (valid) {
        (this.$refs as any).callStrategyRef.validate((valid2) => {
          if (valid2) {
            (this.$refs as any).repeatCallRef.validate((valid3) => {
              if (valid3) {
                let tip = '更新成功!'
                let queryUrl = '/call/action/autoCallTask/update'
                const errMessage = this.handleStrToNumber()
                if (errMessage) {
                  this.$message({ message: errMessage, type: 'error' })
                  return false
                }
                const queryData = cloneDeep(Object.assign({ repeatCallConfig: this.repeatCallConfig, callStrategy: this.callStrategy }, this.baseFrom))
                if (this.drawerData.type === 'add') {
                  tip = '创建成功'
                  queryUrl = '/call/action/autoCallTask/create'
                  delete queryData._id
                }
                const actionData = {
                  url: queryUrl,
                  method: 'POST',
                  data: queryData
                }
                commonAction(actionData).then(resp => {
                  if (resp && resp.success) {
                    this.$message({ message: tip, type: 'success' })
                    this.drawer = !this.drawer
                    this.$emit('updateInfoSuccess', queryData)
                  }
                }).catch(err => { console.log(err) })
              } else {
                return false
              }
            })
          } else {
            return false
          }
        })
      } else {
        return false
      }
    })
  }

  private resetForm (formName) {
    (this.$refs as any)[formName].resetFields()
  }

  private mounted () {
    this.$getCache('/call/action/general/query', ['ivrList', 'timeConditionList', 'displayNumerList', 'groupList'], false, false).then((res: any) => { // 语音导航，时间条件，外显号
      if (res && res.success) {
        this.voiceNavArr = res.ivrList || []
        this.timeConditionList = res.timeConditionList || []
        this.displayNumerList = res.displayNumerList || []
        this.groupList = res.groupList || []
      }
    })
  }

  private beforeMount () {
    const account = this.$store.state.common.session.account
    this.concurrentStr = account ? `账户最大可用并发为 ${account.maxAutoCallTaskConcurrent || 0}` : ''
  }
}
</script>

<style lang="stylus" scoped>
  .tip-span
    color $icon-gray
    cursor pointer
    margin-left 8px
    font-size 14px
  .repeat-call
    border-top 1px solid $border-main
    padding-top 12px
    margin-bottom 12px
    >>>.el-switch__label *
      font-size 14px
      color $fc-gray2
  .repeat-call-ul
    margin-bottom 20px
    li
      width 50%
      color $fc-gray2
      line-height 32px
      text-align center
    .interval-span
      width 70%
      display inline-block
      background $bgc-gray
      box-sizing border-box
      border 1px solid $border-main
    .time-span
      width 30%
      background $bgc-gray
      display inline-block
      box-sizing border-box
      border 1px solid $border-main
    .interval-input
      border-right 1px solid $border-main
      border-bottom 1px solid $border-main
      background #fff
      >>>.el-input__inner
        border none
</style>
